package com.wind.hallservice;

import java.lang.ref.WeakReference;
import java.util.Calendar;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

public class HallClockView extends LinearLayout {
	private static final String ANDROID_CLOCK_FONT_FILE = "/system/fonts/AndroidClock.ttf";
	private final static String M24 = "kk:mm";
	private final static String M12 = "hh:mm";
	private static final String ALARM_ALERT_ACTION = "com.android.deskclock.ALARM_ALERT";

	private TextView mTimeView;
	private TextView mDateView;
	private TextView mWeekView;
	private TextView mAmPmView;
	
	private TextView mMissedCallView;
	private TextView mMissedMmsView;
	private TextView mAlarmClockView;

	private CharSequence mDateFormatString;
	private CharSequence mWeekFormatString;

	private Handler mHandler = new Handler(Looper.myLooper());
	private BroadcastReceiver mIntentReceiver;
	private Calendar mCalendar;
	
	private int mMissedCall = 0;
	private int mMissedMms = 0;
	private Context mContext;

	public HallClockView(Context context, AttributeSet attrs,
			int defStyle) {
		super(context, attrs, defStyle);
        mContext = context;
		Resources res = getContext().getResources();
		mDateFormatString = getDateFormat(res);
		mWeekFormatString = res.getText(R.string.month_day_no_year_week);
	}

	public HallClockView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public HallClockView(Context context) {
		this(context, null, 0);
	}

	@Override
	protected void onFinishInflate() {
		super.onFinishInflate();

		mTimeView = (TextView) findViewById(R.id.keyguard_clock_time);
		mDateView = (TextView) findViewById(R.id.keyguard_clock_date);
		mWeekView = (TextView) findViewById(R.id.keyguard_clock_week);
		mAmPmView =(TextView) findViewById(R.id.keyguard_clock_ampm);
		
		mMissedCallView = (TextView) findViewById(R.id.keygaurd_missed_call);
		mMissedMmsView = (TextView) findViewById(R.id.keygaurd_missed_mms);
		mAlarmClockView = (TextView) findViewById(R.id.keygaurd_alarm_clock);

		mTimeView.setTypeface(Typeface.createFromFile(ANDROID_CLOCK_FONT_FILE));
		mDateView.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
		mWeekView.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
		mAmPmView.setTypeface(Typeface.SANS_SERIF,Typeface.BOLD);
	}

	@Override
	protected void onAttachedToWindow() {
		super.onAttachedToWindow();

		/* monitor time ticks, time changed, timezone */
		if (mIntentReceiver == null) {
			mIntentReceiver = new TimeChangedReceiver(this);
			IntentFilter filter = new IntentFilter();
			filter.addAction(Intent.ACTION_TIME_TICK);
			filter.addAction(Intent.ACTION_TIME_CHANGED);
			filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
			filter.addAction(ALARM_ALERT_ACTION);
			getContext().registerReceiver(mIntentReceiver, filter);
		}

		updateTime();
	}

	@Override
	protected void onDetachedFromWindow() {
		super.onDetachedFromWindow();

		if (mIntentReceiver != null) {
			getContext().unregisterReceiver(mIntentReceiver);
		}
		mIntentReceiver = null;
	}
	
	public void setMissedInfo(int missedCall, int missedMms){
		mMissedCall = missedCall;
		mMissedMms = missedMms;
		
		updateMissedInfo();
	}

	private void updateTime() {
		mCalendar = Calendar.getInstance();
		CharSequence time;
		CharSequence ampm;
		if(DateFormat.is24HourFormat(mContext))
		{
		 time= DateFormat.format(M24, mCalendar);
		 mAmPmView.setText("");
		}
		else
		{
		  time = DateFormat.format(M12, mCalendar);
		  ampm = DateFormat.format("a", mCalendar);
		  mAmPmView.setText(ampm);
		}
		CharSequence date = DateFormat.format(mDateFormatString, mCalendar);
		CharSequence week = DateFormat.format(mWeekFormatString, mCalendar);
		mTimeView.setText(time);
		mDateView.setText(date);
		mWeekView.setText(week);
		
		updateAlarmClock();
	}
	
	private void updateMissedInfo(){
		if(mMissedCall > 0){
			mMissedCallView.setText(mMissedCall + "");
			mMissedCallView.setVisibility(View.VISIBLE);
		}else{
			mMissedCallView.setVisibility(View.GONE);
		}
		
		if(mMissedMms > 0){
			mMissedMmsView.setText(mMissedMms + "");
			mMissedMmsView.setVisibility(View.VISIBLE);
		}else{
			mMissedMmsView.setVisibility(View.GONE);
		}
	}
	
	private void updateAlarmClock(){
		String alarmInfo = Settings.System.getString(getContext()
				.getContentResolver(), Settings.System.NEXT_ALARM_FORMATTED);
		Log.d("wuguohu", "alarmInfo: " + alarmInfo);
		if(alarmInfo != null && !"".equals(alarmInfo)){
			mAlarmClockView.setText(alarmInfo);
			mAlarmClockView.setVisibility(View.VISIBLE);
		}else{
			mAlarmClockView.setVisibility(View.GONE);
		}
	}
	
	private String getDateFormat(Resources res){
		//String formatStr = "EEE, MMMM dd";//res.getString(com.android.internal.R.string.icu_abbrev_wday_month_day_no_year);
        String formatStr = "MM/dd";
		//formatStr = formatStr.replaceAll("[E,]+", "");
		//formatStr = formatStr.trim();
		
		return formatStr;
	}

	private class TimeChangedReceiver extends BroadcastReceiver {
		private WeakReference<HallClockView> mClock;
		private Context mContext;

		public TimeChangedReceiver(HallClockView clock) {
			mClock = new WeakReference<HallClockView>(clock);
			mContext = clock.getContext();
		}

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			final boolean timezoneChanged = action
					.equals(Intent.ACTION_TIMEZONE_CHANGED);
			final HallClockView clock = mClock.get();
			if (clock != null) {
				if (ALARM_ALERT_ACTION.equals(action)) {
					clock.mHandler.post(new Runnable(){

						@Override
						public void run() {
							clock.updateAlarmClock();
						}
						
					});
				}else{
					clock.mHandler.post(new Runnable() {
						public void run() {
							if (timezoneChanged) {
								clock.mCalendar = Calendar.getInstance();
							}
							clock.updateTime();
						}
					});
				}
			} else {
				try {
					mContext.unregisterReceiver(this);
				} catch (RuntimeException e) {
					// Shouldn't happen
				}
			}
			
		}
	};

}
